package hrms.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import hrms.entity.Admin;
import hrms.service.AdminService;
import hrms.util.LogUtil;
import hrms.util.Result;

@Controller
public class LoginController {
	@Resource(name = "adminService")
	private AdminService service;

	@ExceptionHandler
	public String exHandle(Exception ex, HttpServletRequest req) {
		LogUtil.saveEx(ex);
		return "error";
	}

	@RequestMapping("/toLogin.sls")
	public String toLogin() {
		return "main/login";
	}

	@ResponseBody
	@RequestMapping("/login.sls")
	public Result<Admin> login(HttpServletRequest req, HttpSession session) {
		String adminCode = req.getParameter("adminCode");
		String pwd = req.getParameter("password");
		Result<Admin> result = service.check(adminCode, pwd);
		Admin admin = result.getData();
		if(admin != null){
			session.setAttribute("admin", admin);
		}
		return result;
	}

	@RequestMapping("/toIndex.sls")
	public String toIndex() {
		return "main/index";
	}
	
	@RequestMapping("/out.sls")
	public String out(HttpServletRequest req){
		service.outLog(req);
		req.getSession().invalidate();
		return "main/login";
	}
	
	@RequestMapping("/error.sls")
	public String error(){
		return "error";
	}
	
}
